using System.IO;
using UnityEditor;

namespace UnityXEditor
{
    public class EditorFileTool
    {
        /// <summary>
        /// 拷贝目录
        /// </summary>
        /// <param name="sourceDir">源目录</param>
        /// <param name="destDir">目的目录</param>
        /// <param name="withoutMeta">不包含.meta文件</param>
        public static void CopyDirectory(string sourceDir, string destDir, bool withoutMeta = true)
        {
            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }
            foreach (var file in Directory.GetFiles(sourceDir))
            {
                if (withoutMeta == false || Path.GetExtension(file).ToLower() != ".meta")
                {
                    File.Copy(file, Path.Combine(destDir, Path.GetFileName(file)), true);
                }
            }
            foreach (var dir in Directory.GetDirectories(sourceDir))
            {
                CopyDirectory(dir, Path.Combine(destDir, Path.GetFileName(dir)), withoutMeta);
            }
        }

        /// <summary>
        /// 根据文件名获取文件路径
        /// </summary>
        /// <param name="name">带后缀的文件名</param>
        /// <param name="packageName">限定路径名，如若全局搜索，请设置此值为assets，必须全部小写。</param>
        /// <returns>文件路径或null</returns>
        public static string GetFilePath(string name, string packageName = "unityx")
        {
            string[] guids = AssetDatabase.FindAssets(Path.GetFileNameWithoutExtension(name));
            foreach (string guid in guids)
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);
                if (path.ToLower().Contains(packageName) && Path.GetFileName(path) == name)
                {
                    return Path.GetFullPath(path);
                }
            }
            return null;
        }

        /// <summary>
        /// 根据文件名获取文件GUID
        /// </summary>
        /// <param name="name">带后缀的文件名</param>
        /// <param name="packageName">限定路径名，如若全局搜索，请设置此值为assets，必须全部小写。</param>
        /// <returns></returns>
        public static string GetFileGUID(string name, string packageName = "unityx")
        {
            string[] guids = AssetDatabase.FindAssets(Path.GetFileNameWithoutExtension(name));
            foreach (string guid in guids)
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);
                if (path.ToLower().Contains(packageName) && Path.GetFileName(path) == name)
                {
                    return guid;
                }
            }
            return null;
        }
    }
}